<template>
  <view class="logistics-card">
    <view class="leading-none text-16px">
      {{ filterRefundStatus(detail.orderStatus).status }}
      <view class="text-s mt-16px"
        >{{ filterRefundStatus(detail.orderStatus).content }}
      </view>
    </view>
    <image :src="filterRefundStatus(detail.orderStatus).img" />
  </view>
  <view class="px-10px py-10px">
    <view class="transport-card">
      <image :src="ossImg('order/line.png')" />
      <view
        class="transport-content"
        v-if="detail.orderStatus === 2 || detail.orderStatus === 3"
        @click="linkTo('/personalPages/order/logisticsDetail?id=' + detail.id)"
      >
        <view class="transport-description">
          该订单已拆分成1个包裹发出，已全部发货，点击可查看详情<image
            class="arrow"
            :src="ossImg('personal/go@2x.png')"
          />
        </view>

        <view class="transport-address">
          <view class="mb-10px">亿滋奥利奥小程序 021-69768683</view>
          <view>上海市上海市青浦区新业路588号【YC01】</view>
        </view>
      </view>
    </view>
  </view>
  <view class="address-card">
    <view class="flex items-center">
      <view class="order-tag">收货地址</view>
      <view class="address-contract">
        <label>{{ detail.receiverName }}</label>
        {{ detail.receiverPhone }}
      </view>
    </view>
    <view class="address-detail"
      >{{ detail.receiverProvince }}{{ detail.receiverCity
      }}{{ detail.receiverRegion }}{{ detail.receiverDetailAddress }}
    </view>
  </view>
  <view class="py-10px px-10px">
    <view class="pay-info">
      <view v-for="item in detail.items" :key="item.id" class="mb-10px">
        <view class="flex goodsItem">
          <view
            class="goodCheckBox"
            @click.stop="item.selectStatus = !item.selectStatus"
            v-if="
              isRefunds &&
              (item.refundStatus === 0 ||
                item.refundStatus === null ||
                item.refundStatus === 8)
            "
          >
            <view
              class="goods-checkbox"
              :class="{ checked: item.selectStatus }"
            ></view>
          </view>

          <view
            class="goods-cover cover"
            :style="{ backgroundImage: `url(${item.productImageUrl})` }"
          ></view>
          <view class="flex" style="width: 100%">
            <view class="goods-name">
              {{ item.productName }}
            </view>
            <view class="order-total">
              <view class="goods-price">¥{{ item.productSkuPrice || 0 }}</view>
              <view class="goods-count">x{{ item.productSkuQuantity }}</view>
            </view>
          </view>
        </view>

        <view
          class="pay-handle"
          v-if="
            detail.orderStatus === 1 ||
            detail.orderStatus === 2 ||
            detail.orderStatus === 3 ||
            (detail.orderStatus === 4 && item.refundStatus === 6)
          "
        >
          <view @click="refundTo(item)">{{
            filterRefundStatusText(item.refundStatus)
          }}</view>
        </view>
      </view>

      <view class="pay-info__line">
        <label>商品金额：</label>
        <view class="price">
          <view class="master">{{ detail.totalAmount }}</view>
        </view>
      </view>
      <view class="pay-info__line">
        <label>运费：</label>
        <view>
          <view class="master">{{
            detail.freightAmount === 0 ? "包邮" : "¥" + detail.freightAmount
          }}</view>
        </view>
      </view>
      <view class="pay-info__line">
        <label>商品优惠：</label>
        <view class="price">
          <view class="master">{{ detail.couponAmount }}</view>
        </view>
      </view>
      <view class="pay-info__line" style="margin-bottom: 5px">
        <label>实付金额（含运费）：</label>
        <view class="price text-primary">
          <view class="master">{{
            cal.jia(detail.finalAmount, detail.freightAmount)
          }}</view>
        </view>
      </view>
      <view class="payment" v-if="detail.payType === 1">
        <view class="flex justify-between">
          <label>微信支付：</label>
          ¥{{ cal.jia(detail.finalAmount, detail.freightAmount) }}
        </view>
        <image :src="ossImg('order/payment.png')" />
      </view>
    </view>
    <view class="order-info my-12px">
      <label>订单信息</label>
      <view
        >订单编号：{{ detail.orderSn }}
        <image
          :src="ossImg('personal/copy.png')"
          class="orderIdCopy"
          @click="orderIdCopy(detail.orderSn)"
      /></view>
      <view>下单时间：{{ detail.createTime }}</view>
      <view>付款时间：{{ detail.payTime }}</view>
    </view>
  </view>
  <view class="order-handle" v-if="detail.orderStatus !== 1">
    <button
      @click="linkTo('/personalPages/order/logisticsDetail?id=' + detail.id)"
      v-if="detail.orderStatus === 2"
    >
      查看物流
    </button>
    <button
      class="primary"
      @click="ConfirmReceive(detail.id)"
      v-if="detail.orderStatus === 2"
    >
      确认收货
    </button>

    <button
      class="primary"
      v-if="detail.orderStatus === 0 || detail.orderStatus === 6"
      @click.stop="toPay(detail.id)"
    >
      立即付款
    </button>
    <button
      v-if="detail.orderStatus === 0 || detail.orderStatus === 6"
      @click.stop="cancel(detail.id)"
    >
      取消订单
    </button>
    <button
      class="delete"
      v-if="
        detail.orderStatus === 3 ||
        detail.orderStatus === 4 ||
        detail.orderStatus === 5
      "
      @click.stop="deleOrder(detail.id)"
    >
      删除订单
    </button>
  </view>

  <view class="order-handle" v-else>
    <view
      v-if="isRefunds === true"
      class="selectAll flex items-center text-s text-goods"
      @click.stop="onChangeSelectAll"
    >
      <view class="goods-checkbox" :class="{ checked: isAllselect }"></view>
      <view>全选</view>
    </view>

    <button @click="isRefunds = !isRefunds">
      {{ isRefunds === false ? "批量退款" : "取消" }}
    </button>
    <button class="primary" v-if="isRefunds === true" @click="submitRefund">
      确定
    </button>
  </view>
</template>

<script setup>
import { ref, watch } from "vue";
import { onLoad, onShow, onUnload, onHide } from "@dcloudio/uni-app";
import {
  GetOrderDetail,
  receiveConfirm,
  wxOrderPurchase,
  cancelOrder,
  deleteOrder,
} from "@/services/mall";
import { getSettingMall } from "@/services/home";
import { orderStatusFilter, debounce } from "@/utils/utils";
import { ossImg } from "@/utils/utils";
import { message } from "@/utils/utils";
import { Subscribe } from "@/services/utils";
import { cal } from "@/utils/cal";
let enterTime = "";
let outTime = "";
let stayTime = "";
const orderId = ref("");
const detail = ref({});
const isRefunds = ref(false);
const isAllselect = ref(false);
const confirmReceiptForDelivery = ref(0);

watch(
  () => detail.value.items,
  () => {
    if (isRefunds.value === false) return;
    if (detail.value.items.every((val) => val.selectStatus === true)) {
      isAllselect.value = true;
    } else {
      isAllselect.value = false;
    }
  },
  {
    immediate: true, // 这个属性是重点啦
    deep: true, // 深度监听的参数
  }
);

onLoad((option) => {
  console.log(option);
  orderId.value = option.id;
});

const GetDetail = async (id) => {
  const res = await GetOrderDetail(id);
  if (res?.code === 200) {
    for (const item of res.data.items) {
      Object.assign(item, {
        selectStatus: false,
      });
    }
    detail.value = res.data;
    console.log(detail.value);
  }
};

onShow(() => {
  getTiem();
  GetDetail(orderId.value);
  isRefunds.value = false;
  isAllselect.value = false;
  getApp().accessLogAdd();
  // 用户进入时间
  enterTime = new Date();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;

  getApp().emdlz(
    "track",
    "event",
    "store_page",
    "view",
    `order_detail_page_${detail.value.id}_${detail.value.finalAmount}`,
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "store_page",
    "view",
    `order_detail_page_${detail.value.id}_${detail.value.finalAmount}`,
    stayTime
  );
});

const getTiem = async () => {
  const res = await getSettingMall({ key: "trade" });
  if (res?.code === 200) {
    confirmReceiptForDelivery.value = res.data.confirmReceiptForDelivery;
  }
};

const linkTo = (url) => uni.navigateTo({ url });

const refundTo = (item) => {
  console.log(item.refundStatus);
  uni.requestSubscribeMessage({
    tmplIds: [
      process.env.REFUNDSUCCESSNOTICE,
      process.env.AUDITRESULTNOTICE,
      process.env.RETURNREVIEWNOTICE,
    ],
    success: async (res2) => {
      console.log(res2);
      // 订阅成功
      getApp().emdlz(
        "track",
        "event",
        "store_page",
        "click",
        `refund_apply_${item.orderId}_${item.id},${item.productSkuId}`,
        `${item.productSkuPrice}`
      );
      getApp()
        .sr()
        .track("custom_order", {
          order: {
            order_id: item.orderId,
            order_time: Date.now(),
            order_status: "refund",
          },
          sub_orders: [
            {
              sub_order_id: item.orderId,
              order_amt: item.productSkuPrice * item.productSkuQuantity,
              pay_amt:
                item.productSkuPrice * item.productSkuQuantity -
                item.subCouponAmount,
            },
          ],
          // more...
        });

      await Subscribe({
        appId: process.env.WXAPPID,
        orderId: detail.value.id,
        scene: ["REFUND_SUCCEED", "REFUND_ACCEPT", "REFUND_REJECT"],
      });

      if (
        item.refundStatus === 0 ||
        item.refundStatus === null ||
        item.refundStatus === 8
      ) {
        const goodsIdList = [item.id];
        console.log(goodsIdList, goodsIdList.join(","));
        linkTo(
          "/personalPages/order/refundType?orderId=" +
            orderId.value +
            "&goodsId=" +
            goodsIdList.join(",")
        );
      } else {
        linkTo("/personalPages/order/refundDetail?id=" + item.id);
      }
    },
    fail: function (err) {
      console.log(err);
    },
  });
};

const filterRefundStatus = (type) => {
  let obj = {
    img: "",
    status: "",
    content: "",
  };
  switch (type) {
    case 0:
      obj = {
        img: ossImg("order/toBePaid.png"),
        status: orderStatusFilter(type),
        content: "商家已接单，即将发货",
      };
      break;
    case 1:
      obj = {
        img: ossImg("order/toBeShipped.png"),
        status: orderStatusFilter(type),
        content: "商家已接单，即将发货",
      };
      break;
    case 2:
      obj = {
        img: ossImg("order/toBeReceived.png"),
        status: orderStatusFilter(type),
        content: `商家已发货，${confirmReceiptForDelivery.value}天后自动确认收货`,
      };
      break;
    case 3:
      obj = {
        img: ossImg("order/successfulTrade.png"),
        status: orderStatusFilter(type),
        content: "",
      };
      break;

    case 4:
      obj = {
        img: ossImg("order/transactionClosing.png"),
        status: orderStatusFilter(type),
        content: detail.value.items.every((val) => val.refundStatus === 0)
          ? "超时未支付"
          : "已退款",
      };
      break;

    case 6:
      obj = {
        img: ossImg("order/toBePaid.png"),
        status: orderStatusFilter(type),
        content: "",
      };
      break;

    default:
      break;
  }

  return obj;
};

const filterRefundStatusText = (type) => {
  let text = "";
  switch (true) {
    case type === 1 ||
      type === 2 ||
      type === 3 ||
      type === 4 ||
      type === 5 ||
      type === 41 ||
      type === 31:
      text = "退款中";
      break;
    case type === 6:
      text = "退款成功";
      break;

    default:
      text = "申请退款";
      break;
  }
  return text;
};

// 立即支付
const toPay = async (id) => {
  getApp().emdlz(
    "track",
    "event",
    "store_page",
    "click",
    `order_pay_${id}`,
    `${detail.value.finalAmount}`
  );
  getApp()
    .sr()
    .track("custom_order", {
      order: {
        order_id: detail.value.id,
        order_time: Date.now(),
        order_status: "pay",
      },
      sub_orders: [
        {
          sub_order_id: detail.value.id,
          order_amt: detail.value.totalAmount,
          pay_amt: detail.value.finalAmount,
        },
      ],
      // more...
    });

  const res = await wxOrderPurchase({ id, appId: process.env.WXAPPID });
  if (res?.code === 200) {
    uni.requestPayment({
      provider: "wxpay", //支付类型-固定值
      timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
      nonceStr: res.data.nonceStr, // 随机字符串
      package: res.data.package, // 固定值
      signType: res.data.signType, //固定值
      paySign: res.data.paySign, //签名
      success: async function (res) {
        console.log("success:" + JSON.stringify(res));
        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: detail.value.id,
              order_time: Date.now(),
              order_status: "payed",
            },
            sub_orders: [
              {
                sub_order_id: detail.value.id,
                order_amt: detail.value.totalAmount,
                pay_amt: detail.value.finalAmount,
              },
            ],
            // more...
          });
        await message("支付成功", 1000);
        uni.reLaunch({
          url: "/pages/paySuccess/index",
        });
      },
      fail: function (err) {
        console.log("fail:" + JSON.stringify(err));
        console.log("支付失败");
        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: detail.value.id,
              order_time: Date.now(),
              order_status: "cancel_pay",
            },
            sub_orders: [
              {
                sub_order_id: detail.value.id,
                order_amt: detail.value.totalAmount,
                pay_amt: detail.value.finalAmount,
              },
            ],
            // more...
          });
        uni.showModal({
          title: "确定取消支付吗？",
          content: "120分钟内未付款，订单将自动关闭，请尽快付款哦！",
          cancelText: "稍后付款",
          confirmText: "继续付款",
          success: function (res) {
            if (res.confirm) {
              console.log("用户点击确定");
              toPay(id);
            } else if (res.cancel) {
              console.log("用户点击取消");
              message("取消支付");
            }
          },
        });
      },
    });
  } else {
    message(res.message);
  }
};

// 取消订单
const cancel = debounce(
  async (id) => {
    getApp().emdlz(
      "track",
      "event",
      "store_page",
      "click",
      `order_cancel_${detail.value.id}`,
      `${detail.value.finalAmount}`
    );

    const res = await cancelOrder({ id: id });
    if (res?.code === 200) {
      getApp()
        .sr()
        .track("custom_order", {
          order: {
            order_id: detail.value.id,
            order_time: Date.now(),
            order_status: "cancel_give_order",
          },
          sub_orders: [
            {
              sub_order_id: detail.value.id,
              order_amt: detail.value.totalAmount,
              pay_amt: detail.value.finalAmount,
            },
          ],
          // more...
        });
      await message("取消成功", 2000);
      reload();
    } else {
      message(res.message);
    }
  },
  500,
  false
);

// 删除订单
const deleOrder = debounce(
  (id) => {
    uni.showModal({
      content: "确定是否删除此订单？",
      success: async function (res) {
        if (res.confirm) {
          console.log("用户点击确定");
          const res = await deleteOrder(id);
          if (res?.code === 200) {
            await message("删除成功", 2000);
            uni.navigateBack({
              delta: 1,
            });
            message(res.message);
          }
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  500,
  false
);

// 确认收货
const ConfirmReceive = debounce(
  async (id) => {
    const res = await receiveConfirm({ id: id });
    if (res?.code === 200) {
      await message("确认收货", 2000);
      reload();
    } else {
      message(res.message);
    }
  },
  500,
  false
);

const reload = () => {
  // 页面重载
  const pages = getCurrentPages();
  // 声明一个pages使用getCurrentPages方法
  const curPage = pages[pages.length - 1];
  // 声明一个当前页面
  curPage.onLoad(curPage.options); // 传入参数
  curPage.onShow();
  curPage.onReady();
  // 执行刷新
};

const onChangeSelectAll = () => {
  isAllselect.value = !isAllselect.value;
  if (isAllselect.value === true) {
    detail.value.items.map((val) => (val.selectStatus = true));
  } else {
    detail.value.items.map((val) => (val.selectStatus = false));
  }
};

const orderIdCopy = (e) => {
  uni.setClipboardData({
    data: e, // e是你要保存的内容
    success: function () {
      uni.showToast({
        title: "复制成功",
        icon: "none",
      });
    },
  });
};

const submitRefund = () => {
  const goodsList = [];
  detail.value.items.map((val) => {
    if (
      val.refundStatus === 0 ||
      val.refundStatus === null ||
      val.refundStatus === 8
    ) {
      if (val.selectStatus === true) {
        goodsList.push(val.id);
      }
    }
  });
  linkTo(
    "/personalPages/order/refundType?orderId=" +
      orderId.value +
      "&goodsId=" +
      goodsList.join(",")
  );
  console.log(goodsList);
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.order-recommend {
  width: 100%;
  height: 165px;
  background-color: rgba(0, 0, 0, 0.1);
}

.order-info {
  padding: 12px 8px;
  box-sizing: border-box;
  background-color: white;
  line-height: 1;
  font-size: 14px;
  color: #353535;

  view {
    color: #b8b8b8;
    margin-top: 8px;
  }

  .orderIdCopy {
    width: 16px;
    height: 16px;
    float: right;
  }
}

.pay-info {
  background-color: white;
  padding: 12px 8px 14px 8px;
  box-sizing: border-box;

  .goods-cover {
    width: 68px;
    min-width: 68px;
    height: 68px;
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0.2);
  }

  .goods-name {
    padding: 0 12px 0 8px;
    box-sizing: border-box;
    font-size: 14px;
    flex: 1;
    color: #353535;
  }

  .order-total {
    color: #353535;
    text-align: right;
    font-size: 14px;

    .goods-count {
      font-size: 12px;
      color: #818181;
      line-height: 1;
      margin-top: 5px;
    }
  }

  .pay-handle {
    padding-top: 2px;
    padding-bottom: 23px;
    display: flex;
    justify-content: flex-end;

    view {
      width: 60px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      background: #ffffff;
      border: 1px solid #2c2c2c;
      border-radius: 12px;
      font-size: 12px;
      color: #1b1b1b;
    }
  }

  .pay-info__line {
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 1;
    margin-bottom: 12px;
    font-size: 14px;
    color: #353535;

    label {
      font-size: 14px;
    }
  }

  .payment {
    height: 54px;
    box-sizing: border-box;
    padding: 0 10px;
    position: relative;

    view {
      z-index: 1;
      position: relative;
      font-size: 14px;
      padding-top: 23px;
      line-height: 1;
      color: #353535;
    }

    image {
      width: 100%;
      height: inherit;
      position: absolute;
      top: 0;
      right: 0;
    }
  }
}

.transport-card {
  image {
    width: 100%;
    height: 10px;
    display: block;
  }

  .transport-content {
    padding: 18px 8px 10px 8px;
    box-sizing: border-box;
    background-color: white;
    font-size: 12px;

    .transport-description {
      color: @primary-color;
      margin-bottom: 24px;
      .arrow {
        width: 10rpx;
        height: 18rpx;
        display: inline-block;
        margin-left: 10px;
      }
    }

    .transport-address {
      padding: 14px 8px;
      color: #7d7d7d;
      box-sizing: border-box;
      background-color: #f8f8f8;
      line-height: 1;
    }
  }
}

.address-card {
  padding: 24px 20px;
  background-color: white;
  box-sizing: border-box;

  .address-contract {
    font-size: 12px;
    color: #9c9c9c;

    label {
      font-size: 16px;
      color: @label-color;
      padding: 0 5px 0 8px;
    }
  }

  .address-detail {
    line-height: 1;
    font-size: 12px;
    color: @label-color;
    margin-top: 11px;
  }
}

.logistics-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: @primary-color;
  padding: 19px 47px 18px 24px;
  box-sizing: border-box;
  background-color: white;

  image {
    width: 57px;
    height: 57px;
  }
}

.order-handle {
  width: 100%;
  height: 64px;
  display: flex;
  justify-content: flex-end;
  background-color: white;
  z-index: 99;
  position: sticky;
  bottom: 0;
  left: 0;
  box-sizing: border-box;
  padding: 16px 12px 0 12px;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  button {
    margin: 0;
    margin-left: 12px;
    width: 80px;
    height: 32px;
    line-height: 31px;
    background: #ffffff;
    border: 1px solid #404040;
    border-radius: 32px;
    font-size: 14px;
    color: #363636;
    padding: 0;
    &.delete {
      color: @label-color;
      border-color: @label-color;
    }
    &.primary {
      color: @primary-color;
      border-color: @primary-color;
    }

    &::after {
      border: none;
    }
  }
}

.goodCheckBox {
  display: flex;
  width: 18px;
  justify-content: center;
  height: 68px;
  margin-right: 8px;
  align-items: center;
}
.goods-checkbox {
  width: 18px;
  min-width: 18px;
  height: 18px;
  border-radius: 16px;
  box-sizing: border-box;
  border: 1px solid @primary-color;

  &.checked {
    border: none;
    background: url("@{ossPath}others/component/checkbox.png") no-repeat center /
      100% 100%;
  }
}

.selectAll {
  height: 32px;
  position: absolute;
  left: 20px;
  .goods-checkbox {
    margin-right: 5px;
  }
}
</style>
